package model;

import lock.ConcreteLock;
import lock.Lock;

public class StepperManager extends Observable{

	private final Lock resultLock;
	private Result result;
	private final Automaton automaton;
	
	public StepperManager(final Automaton automaton, final Configuration configuration) {
		this.resultLock = new ConcreteLock(true);
		final Stepper firstBranchRunnable = new Stepper(configuration, this);
		new Thread(firstBranchRunnable).start();
		this.automaton = automaton;
	}

	public Result getResult() {
		this.getResultLock().lock();
		final Result result = this.result;
		this.getResultLock().unlock();
		return result;
	}

	public Lock getResultLock() {
		return resultLock;
	}


	public void getBranchResult(final Result result){
		result.accept(new ResultVisitor() {
			
			@Override
			public void visit(final RecognizedResult result) {
				StepperManager.this.setResult(result);
				StepperManager.this.notifyObservers();
			}
			
			@Override
			public void visit(final NotRecognizedResult result) {
				// TODO Auto-generated method stub
				if(StepperManager.this.getObservers().isEmpty()){
					StepperManager.this.setResult(result);
				}
			}
		});
	}

	public void setResult(final Result result) {
		this.result = result;
		this.getResultLock().unlock();
	}

	public Automaton getAutomaton() {
		return automaton;
	}

	
	
}
